const sharp = require('sharp')
const path = require('path')
const fs = require('fs').promises
const { PDFDocument } = require('pdf-lib')

// 生成图片缩略图
async function generateImageThumbnail(inputPath, outputPath, size = 200) {
  try {
    await sharp(inputPath)
      .resize(size, size, {
        fit: 'inside',
        withoutEnlargement: true
      })
      .toFile(outputPath)
    return true
  } catch (error) {
    console.error('生成图片缩略图失败:', error)
    throw error
  }
}

// 生成PDF缩略图
async function generatePDFThumbnail(inputPath, outputPath, size = 200) {
  try {
    // 读取PDF文件
    const pdfBytes = await fs.readFile(inputPath)
    const pdfDoc = await PDFDocument.load(pdfBytes)
    
    // 获取第一页
    const page = pdfDoc.getPages()[0]
    const { width, height } = page.getSize()
    
    // 计算缩放比例
    const scale = Math.min(size / width, size / height)
    
    // 创建新PDF文档
    const thumbnailDoc = await PDFDocument.create()
    const [thumbnailPage] = await thumbnailDoc.copyPages(pdfDoc, [0])
    thumbnailDoc.addPage(thumbnailPage)
    
    // 调整页面大小
    thumbnailPage.setSize(width * scale, height * scale)
    
    // 保存缩略图
    const thumbnailBytes = await thumbnailDoc.save()
    await fs.writeFile(outputPath, thumbnailBytes)
    
    return true
  } catch (error) {
    console.error('生成PDF缩略图失败:', error)
    throw error
  }
}

// 生成文档缩略图
async function generateThumbnail(inputPath, outputPath) {
  const ext = path.extname(inputPath).toLowerCase()
  
  try {
    if (['.jpg', '.jpeg', '.png'].includes(ext)) {
      return await generateImageThumbnail(inputPath, outputPath)
    } else if (ext === '.pdf') {
      return await generatePDFThumbnail(inputPath, outputPath)
    }
    
    // 不支持的文件类型生成默认缩略图
    await generateDefaultThumbnail(outputPath, ext)
    return true
  } catch (error) {
    console.error('生成缩略图失败:', error)
    throw error
  }
}

// 生成默认缩略图
async function generateDefaultThumbnail(outputPath, fileType) {
  const canvas = require('canvas').createCanvas(200, 200)
  const ctx = canvas.getContext('2d')
  
  // 背景
  ctx.fillStyle = '#f5f7fa'
  ctx.fillRect(0, 0, canvas.width, canvas.height)
  
  // 文件类型图标
  ctx.fillStyle = '#409EFF'
  ctx.font = '30px Arial'
  ctx.textAlign = 'center'
  ctx.fillText(fileType.toUpperCase(), canvas.width / 2, canvas.height / 2)
  
  // 保存缩略图
  const out = fs.createWriteStream(outputPath)
  const stream = canvas.createPNGStream()
  stream.pipe(out)
  
  return new Promise((resolve, reject) => {
    out.on('finish', resolve)
    out.on('error', reject)
  })
}

module.exports = {
  generateImageThumbnail,
  generatePDFThumbnail,
  generateThumbnail,
  generateDefaultThumbnail
}